package com.peoject.Controller;

import com.peoject.dao.INoteDao;
import com.peoject.dao.INoteEsDao;
import com.peoject.dto.NoteDto;
import com.peoject.entity.NoteEntity;
import com.peoject.entity.NoteEs;
import com.peoject.entity.ReviewEntity;
import com.peoject.util.ShowIdUtil;
import com.peoject.vo.RestVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("note")
public class NoteController {

    @Autowired
    INoteDao noteDao;
    @Autowired
    INoteEsDao noteEsDao;
    @Autowired
    RedisTemplate<String ,Object> redisTemplate;

    private static  String s;

    @RequestMapping("findItem")
    public Page<NoteDto> findItem(String type, int pageNO) {
        PageRequest p = PageRequest.of(pageNO - 1, 3);
        Page<NoteDto> note = null;
        if (StringUtils.hasLength(type) && type != null) {
            note = noteDao.page(type, p);
        } else {
            note = noteDao.page(p);
        }
        return note;
    }
//    @RequestMapping("findAll")
//    public Page<NoteDto> findAll(int pageNO){
//        PageRequest p = PageRequest.of(pageNO-1, 3);
//
//      return   noteDao.page( p);
//
//    }


    @PostMapping("add")
    @Transactional
    public String add(@RequestBody RestVo vo) {
        s= ShowIdUtil.uniqueLongHex();
        //添加数据库
        NoteEntity noteEntity = new NoteEntity();
        noteEntity.setType(vo.getType());
        noteEntity.setTitle(vo.getTitle());
        noteEntity.setNoteEsId(s);
        noteDao.save(noteEntity);
        //添加es数据
        NoteEs noteEs = new NoteEs();
        noteEs.setType(vo.getType());
        noteEs.setTitle(vo.getTitle());
        noteEs.setInfo(vo.getInfo());
        noteEs.setNoteEsId(s);
        noteEsDao.save(noteEs);
        return "ok";
    }

    @RequestMapping("findById")
    public NoteEs findById(String noteId) {

        return noteEsDao.findById(noteId).get();
    }

    @RequestMapping("findByAllInfo")
    public List<NoteEs> findByAllInfo(String info) {
        return noteEsDao.findAllByInfo(info);
    }
    @Scheduled(cron = "0 13 9 ? * *")
    public void send(){
        //redis数据库
      NoteEs noteEs  =noteEsDao.findById(s).get();
        System.err.println(noteEs);
        ReviewEntity review =new ReviewEntity();
        review.setReviewId(s);
        review.setReviewInfo(noteEs.getInfo());
        review.setReviewTitle(noteEs.getTitle());
        redisTemplate.opsForList().leftPush("logstash-list",review);
    }


}
